﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace AChance.Func
{
    public static class FunTemp
    {
        public static string CurrentPath { get; } = FunContext.CurrentPath + "Temp\\";
        public static bool Init()
        {
            try
            {
                if (!Directory.Exists(CurrentPath))
                    Directory.CreateDirectory(CurrentPath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static void Clear()
        {
            try
            {
                if (!Directory.Exists(CurrentPath))
                    return;
                DirectoryInfo tempPath = new DirectoryInfo(CurrentPath);
                foreach (FileInfo tempFile in tempPath.GetFiles())
                {
                    tempFile.Delete();
                }
            }
            catch { }
        }

        public static void ClearExpired()
        {
            try
            {
                if (!Directory.Exists(CurrentPath))
                    return;
                DirectoryInfo tempPath = new DirectoryInfo(CurrentPath);
                foreach (FileInfo tempFile in tempPath.GetFiles())
                {
                    if (tempFile.LastWriteTime > DateTime.Now.AddHours(-1))
                        continue;
                    tempFile.Delete();
                }
            }
            catch { }
        }

        public static void DeleteFile(string fileName)
        {
            try
            {
                if (!Directory.Exists(CurrentPath))
                    return;
                File.Delete(CurrentPath + fileName);
            }
            catch { }
        }

        private static string CreateFileFullName(string name)
        {
            string strReturn = CurrentPath;
            string strRandom = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            string strFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + strRandom;
            string strExtName = ".tmp";
            if (name.IsNullOrEmpty())
                strReturn += strFileName + strExtName;
            else if (name.Contains("."))
                strReturn += Path.GetFileNameWithoutExtension(name) + "_" + strRandom + Path.GetExtension(name);
            else
                strReturn += strFileName + "." + name;
            return strReturn;
        }

        public static string CreateSysFileFullName(string name)
        {
            return CreateFileFullName(name.ToSysFileName());
        }

        public static string CreateWebFileFullName(string name)
        {
            return CreateFileFullName(name.ToWebFileName());
        }
    }
}
